// 登录与注册仓库

import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogOut } from '@/api';

const state = {
	token: localStorage.getItem('TOKEN'),
	userInfo: {}
};
const mutations = {
	GETUSETLOGIN(state, data) {
		state.token = data.token;
	},
	GETUSETINFO(state, data) {
		state.userInfo = data;
	},
	// 清除本地数据
	CLEAR(state) {
		// 将仓库中相关用户信息清空
		state.token = '';
		state.userInfo = {};
		// 本地存储数据清空
		localStorage.removeItem('TOKEN');
	}
};
const actions = {
	/**
	 * 获取注册验证码
	 */
	async getCode({ commit }, phone) {
		let res = await reqGetCode(phone);
		if (res.code == 200) {
			return res.data;
		} else {
			return Promise.reject('获取失败');
		}
	},
	/**
	 * 注册用户
	 */
	async getUserRegister({ commit }, user) {
		let res = await reqUserRegister(user);
		if (res.code == 200) {
			return 'ok';
		} else {
			return Promise.reject(res.message);
		}
	},
	/**
	 * 登录业务
	 */
	async getUserLogin({ commit }, user) {
		let res = await reqUserLogin(user);
		if (res.code == 200) {
			// 服务器下发token，是用户的唯一标识
			// 将来经常通过带token找服务器要用户的信息进行展示
			commit('GETUSETLOGIN', res.data);
			// 本地持久化存储token
			localStorage.setItem('TOKEN', res.data.token);
			return 'ok';
		} else {
			return Promise.reject('登录失败');
		}
	},
	/**
	 * 获取用户信息
	 */
	async getUserInfo({ commit }) {
		let res = await reqUserInfo();
		if (res.code == 200) {
			commit('GETUSETINFO', res.data);
			return 'ok';
		} else {
			return Promise.reject('获取用户信息失败');
		}
	},
	/**
	 * 退出登录
	 */
	async logOut({ commit }) {
		let res = await reqLogOut();
		if (res.code == 200) {
			// 清除本地数据
			commit('CLEAR');
			return 'ok';
		} else {
			return Promise.reject('退出失败');
		}
	}
};
const getters = {};

export default {
	state,
	mutations,
	actions,
	getters
};
